package com.pactera.jep.service.sys.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.lang3.StringUtils;

/**
 * 自定义MD5加密器
 * 
 * @author ghost
 *
 */
public class MD5Encoder {

	private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
			'f' };

	public final static String encode(String source, String salt, int iteration) {
		if (StringUtils.isEmpty(source)) {
			throw new IllegalArgumentException("source cannot be empty.");
		}
		if (StringUtils.isEmpty(salt)) {
			return hash(source.getBytes(), null, iteration);
		} else {
			return hash(source.getBytes(), salt.getBytes(), iteration);
		}
	}

	private final static String hash(byte[] source, byte[] salt, int iteration) {
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			// 加盐
			if (salt != null) {
				digest.reset();
				digest.update(salt);
			}
			byte[] hashed = digest.digest(source);
			// 迭代对密码进行加密
			while (--iteration > 0) {
				digest.reset();
				hashed = digest.digest(source);
			}
			return toHexString(hashed);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 将byte数组转化成十六进制数据
	 * 
	 * @param data
	 * @return
	 */
	private final static String toHexString(byte[] data) {
		int l = data.length;

		char[] out = new char[l << 1];

		// two characters form the hex value.
		for (int i = 0, j = 0; i < l; i++) {
			out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
			out[j++] = DIGITS[0x0F & data[i]];
		}
		return new String(out);
	}

}
